package com.lfg.leetcode.leetcode100;


import java.util.LinkedList;
import java.util.Queue;

public class No116connect {

    public static void main(String[] args) {
        Node node = new Node(1);
        node.left = new Node(2);
        node.right = new Node(3);

        node.left.left = new Node(4);
        node.left.right = new Node(5);

        node.right.left = new Node(6);
        node.right.right = new Node(7);

        connect(node);
        System.out.println("[" + node + "]");
    }

    public static Node connect(Node root) {
        if(null == root){
            return root;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (true) {
            Node last = null;
            Queue<Node> newQueue = new LinkedList<>();
            while (!queue.isEmpty()) {
                Node node = queue.poll();

                if (last != null) {
                    last.next = node;
                }
                last = node;
                if (node.left != null) {
                    newQueue.offer(node.left);
                }
                if (node.right != null) {
                    newQueue.offer(node.right);
                }
            }
            if (newQueue.isEmpty()) {
                break;
            }
            queue = newQueue;
        }
        return root;
    }
}
